package com.ts.api.module.api.handler;

import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.redis.DataExchangeRedisKey;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.module.api.entity.bo.ApiHeaderBO;
import com.ts.api.module.api.entity.bo.ApiMsgBO;
import com.ts.api.module.api.entity.po.ApiKeyPO;
import com.ts.api.module.api.entity.vo.ReqApiParameterVO;
import com.ts.api.module.api.service.ApiRequestValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *  API接入方-对方接入-处理器
 *
 *  @author Pan
 */
@Component
public class ApiMsgHandler {

    @Autowired
    private ApiRequestValidateService apiRequestValidateService;

    /**
     *  撞库解析实体
     *
     *  @author Pan
     *  @param  requestVO
     *  @return ReqApiParameterVO
     */
    public ReqApiParameterVO handleDataExchangeRequest(RequestVO requestVO) {
        Assert.isNotEmptyThrows(requestVO.getBody(), new ApiMsgException(ApiEnum.API_BODY_ERROR));

        ApiHeaderBO headerBO = apiRequestValidateService.validHeader(requestVO.getHeader());
        ApiKeyPO apiKeyPO = apiRequestValidateService.validClient(headerBO.getClientId());
        ApiMsgBO msgBO = apiRequestValidateService.validSign(headerBO, requestVO.getBody(), apiKeyPO);

        //  记录当前渠道总撞库数
        String apiClientId = apiKeyPO.getApiClientId();
        Long increment = DataExchangeRedisKey.DATA_EXCHANGE_TOTAL.increment(apiClientId);
        if (increment == 1) {
            DataExchangeRedisKey.DATA_EXCHANGE_TOTAL.expire(apiClientId, DateUtils.getTomorrowMidnightMillis(), TimeUnit.MILLISECONDS);
        }

        //  返回
        ReqApiParameterVO reqApiParameterVO = ReqApiParameterVO.createByRequestBody(msgBO.getBody(), apiKeyPO);
        reqApiParameterVO.setServiceCode(msgBO.getServiceCode());
        return reqApiParameterVO;
    }


}
